import axios from 'axios'
import { getToken } from './token'
import $router from '@/router'
import { showToast } from 'vant'
import getSnLoCode from '@/utils/Sn-LoCode'
const service = axios.create({
  baseURL: import.meta.env.VITE_API,
  timeout: 20 * 1000,
})

//请求拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['Authorization'] = 'Bearer ' + getToken('token')
    config.headers['Sn-Platform'] = 'H5'
    config.headers['Sn-LoCode'] = getSnLoCode()
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

//响应拦截器
service.interceptors.response.use(
  async (response: any) => {
    if (response.data.code === 401) {
      await $router.push('/')
    }
    if (response.data.code !== 200) {
      showToast({
        message: response?.data?.message,
      })
      return Promise.reject(response?.data?.message || 'error')
    }
    return response.data
  },
  (error) => {
    showToast({
      type: 'text',
      message: error.message,
    })
    return Promise.reject(error || 'error')
  },
)

export default service
